from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
import datetime

#Ratings can be attached generically to most any object.
class BaseVotingAbstractModel(models.Model):
	
	class Meta:
		unique_together = [('user', 'content_type', 'object_pk')]
        verbose_name = _('vote')
        verbose_name_plural = _('votes')

	# Content-object field
	parent   = models.ForeignKey(ConsensusObject,
			verbose_name=_('content type')
	submit_date = models.DateTimeField(_('date/time submitted'), default=None)
	user		= models.ForeignKey(User, verbose_name=_('user'),
					blank=True, null=True, related_name="%(class)s_ratings")
	user_name	= models.CharField(_("user's name"), max_length=50, blank=True)

#This is the basic voting object utilized within Reddit-like consensus
class UpDownVote(BaseRatingAbstractModel):
	vote_type = models.IntegerField() #For simplicity upvote == 1, downvote == -1, neut == 0
	
	 def __unicode__(self):
			return "%s: %s" % (self.user, self.vote_type)
	
	def save(self, force_insert=False, force_update=False):
		if self.submit_date is None:
			self.submit_date = datetime.datetime.now()
		super(UpDownVote, self).save(force_insert, force_update)
		
#Generic conesensus object that acts as parent for all votes
class ConsensusObject(models.Model):
	
	content_type   = models.ForeignKey(ContentType,
			verbose_name=_('content type'),
			related_name="content_type_set_for_%(class)s")
	object_pk	   = models.TextField(_('object ID'))
	content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
	
	
	
